package com.cqc.retrofitdemo02.http;

import android.util.Log;

import com.cqc.retrofitdemo02.event.HttpErrorEvent;
import com.cqc.retrofitdemo02.event.HttpSuccessEvent;
import com.cqc.retrofitdemo02.event.RequestTag;

import org.greenrobot.eventbus.EventBus;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by cui on 2016/12/23.
 */

public class MainRequest {

    public void postString(Call<String> call, final RequestTag tag) {
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                handleSuccess(response, tag);
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                handleError(t, tag);
            }
        });
    }

    private void handleError(Throwable t, RequestTag tag) {
        Log.d("failure",t.getMessage());
        HttpErrorEvent event = new HttpErrorEvent();
        event.setErrorMessage("未获取到数据");
        EventBus.getDefault().post(event);
    }

    private void handleSuccess(Response<String> response, RequestTag tag) {
        Log.d("response",response.body());
        HttpSuccessEvent event = new HttpSuccessEvent();
        event.setJson(response.body());
        event.setRequestTag(tag);
        EventBus.getDefault().post(event);
    }
}
